package com.zhenmyan.secdeal.rabbitmq;

import com.alibaba.druid.support.json.JSONUtils;
import com.zhenmyan.secdeal.pojo.SecDealMessage;
import com.zhenmyan.secdeal.pojo.User;
import com.zhenmyan.secdeal.service.GoodsService;
import com.zhenmyan.secdeal.service.OrderService;
import com.zhenmyan.secdeal.utils.JsonUtil;
import com.zhenmyan.secdeal.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * description:
 *
 * @author 颜真明
 * @date 2023/5/15  2:05
 */
@Service
@Slf4j
public class MQReceiver {

    @Resource
    private GoodsService goodsService;

    @Resource
    private OrderService orderService;

    /**
     * 消息接收测试
     *
     * @param message
     */
    @RabbitListener(queues = "queue")
    public void receive(String message) {
        System.out.println("normal模式开始接收消息");
        System.out.println("打印消息：" + message);
        log.info("normal模式接收消息：" + message);
    }

    @RabbitListener(queues = "secDealQueue")
    public void secDealReceive(String message) {
        log.info("接收秒杀消息：" + message);
        SecDealMessage secDealMessage = JsonUtil.jsonStr2Object(message, SecDealMessage.class);
        Long goodId = secDealMessage.getGoodId();
        User user = secDealMessage.getUser();
        GoodsVo goodsVo = goodsService.getGoodsVoById(goodId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        orderService.secDeal(user, goodsVo);
    }

}
